package net.zoneland.greenleaf.system.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.zoneland.greenleaf.common.date.DateOperation;
import net.zoneland.greenleaf.common.pagination.Pagination;
import net.zoneland.greenleaf.system.entity.Sys_holidayconf;
import net.zoneland.greenleaf.system.service.Sys_holidayconfServiceI;

/**
 * SYS_HOLIDAYCONF[SYS_HOLIDAYCONF]表操作控制层（Controller|Action）

 * 类   名：Sys_holidayconfController<br/>
 * 表   名：SYS_HOLIDAYCONFCONTROLLER<br/>
 * 注   释：节假日配置表<br/>
 * 作   者：GREENLEAF<br/>
 * 单   位：浙江兰德纵横网络技术有限公司<br/>
 * 日   期：2015-04-28 15:14:22
**/
@Controller
@RequestMapping("sys_holidayconf")
public class Sys_holidayconfController extends BaseController { 

	public boolean monitor = false; 
	private DateOperation dateOperation = new DateOperation();
  	public static Logger logger = Logger.getLogger(Sys_holidayconfController.class);

	//获取类的名称
  	@SuppressWarnings("unused")
	private String clazzName = new Object() {
  		public String getClassName() {
  			String clazzName = this.getClass().getName();
  			return clazzName.substring(0, clazzName.lastIndexOf('$'));
  		}
  	}.getClassName();

	/**
	 * sys_holidayconfService
	 * @param sys_holidayconfService
	**/
	@Autowired
	private Sys_holidayconfServiceI sys_holidayconfService;

	/**
     * 根据ID获取信息数据
     * 
     * @param id
     * @return
     */
    @RequestMapping( method = RequestMethod.GET, value = "/{id}", produces = "text/html;charset=UTF-8" )
    @ResponseBody
    public Object get( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Sys_holidayconf entity = null;
		Boolean check = true;
		
		map.put("id", id);
		if( id == null || "(0)".equals( id ) || id.isEmpty() ){
			check = false;
			map.put("result", "error");
			map.put("message", "系统获取到的ID不正常，ID:" + id );
		}
		if( check ){
			try {
				entity = sys_holidayconfService.get( map );
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据ID获取对象失败!");
				logger.error("系统根据ID获取对象发生异常。ID:" + id, e);
			}
		}
		if( check ){
			if( entity != null ){
				map.put("result", "success");
				map.put( "data", entity );
			}else{
				map.put("result", "error");
				map.put("message", "数据不存在！ID:" + id );
			}
		}
		return map;
	}

    /**
	 * 获取信息表列表
	 * 返回JSON格式数据
	 * 如果不需要分页，您可以考虑将pagesize设置为足够大的数字，系统默认为20
	 * 
	 * @param Map<String, Object> paramMap 
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/list" )
    @ResponseBody
	public Object list( @RequestBody Map<String, Object> paramMap ) {		
		String page = "1";
		Integer pagesize = 20, totalRecord=0;
		List<Sys_holidayconf> list  = null;
		Map<String, Object> map=new HashMap<String,Object>();
		Pagination<?> pagination = null;
		Boolean check = true;
		
		if( paramMap == null ){
			check = false;
			map.put("result", "error");
			map.put("message", "参数列表为空，无法进行数据查询！");
		}
		if( check ){
			if(paramMap.get("page")!=null){
				page = paramMap.get("page").toString();
			}
			if(paramMap.get("pagesize") != null){
				try{
					pagesize = Integer.parseInt(paramMap.get("pagesize").toString());
				}catch(Exception e){
					pagesize = 20;
				}
			}
			if( paramMap.get("c_codes")   != null && paramMap.get("c_codes").toString().trim().length() > 1){
				paramMap.put("c_codes", paramMap.get("c_codes").toString().trim().split(","));
			}
		}
		if( check ){
			try{
				totalRecord = sys_holidayconfService.getListCount( paramMap );
			}catch( Exception e ){
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据条件查询信息数据条目总数时发生异常！");
				logger.error( e );
			}
		}
		if( check ){
			try{
				pagination = Pagination.newPagination( pagesize, page, totalRecord );
				paramMap.put( "startRow", pagination.getStartRow() );
				paramMap.put( "pageSize", pagesize );
				paramMap.put("orderColName", "C_ORDER");
			}catch( Exception e ){
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据条件进行分页信息计算时发生异常！");
				logger.error( e );
			}
		}
		if( check ){		
			if( totalRecord>0 ){
				try{
					list = sys_holidayconfService.getList( paramMap );
				}catch( Exception e ){
					check = false;
					map.put("result", "error");
					map.put("message", "系统根据条件进行信息列表查询信息数据时发生异常！");
					logger.error( e );
				}
			}
		}
		if( check ){
			if( list == null ){
				list = new ArrayList<Sys_holidayconf>();
			}
		}
		if( check ){
			map.put( "result", "success" );
			map.put( "message", "系统查询信息数据成功！" );
			map.put( "pagination", pagination );
			map.put( "data", list );
		}
		return map;
	}
	
	/**
	 * 增加或编辑一个系统配置信息表信息
	 * 
	 * 返回JSON格式数据
	 * @param entity
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/save" )
    @ResponseBody
	public Object save( @RequestBody Sys_holidayconf entity ){
		Map<String, Object> map = new HashMap<String, Object>();
		
		Boolean check = true;
		
		if( entity == null ){
			check = false;
			map.put("result", "error");
			map.put("message", "需要保存的信息数据为空!");
		}
		if( check ){
			map = validate( entity, map );
			if( map.get( "result" ) == null || "error".equalsIgnoreCase( map.get( "result" ).toString() ) ){
				check = false;
			}
		}
		
		if( check ){
			try{
				sys_holidayconfService.addOrUpdate( entity );
				map.put("result", "success");
				map.put("message", "保存信息成功！");
				map.put( "data", entity );
			}catch(Exception e){
				map.put("result", "error");
				map.put("message", "保存信息数据失败!");
				logger.error("保存信息数据失败", e);
			}
		}
		return map;
	}
	
	/**
	 * 对需要进行保存的对象里德信息校验
	 * @param entity
	 * @param map 
	 * @return
	 */
	private Map<String, Object> validate( Sys_holidayconf entity, Map<String, Object> map ) {
		Date starttime = null;
		map.put("result", "success");
		
		//TODO 这里进行所有的数据校验工作
		if( entity.getType() == 0 || entity.getType() == 1 ){
			try{
				//对开始时间和结束时间进行转换，检查时间有效性，并且填写年份
				starttime = dateOperation.getDateFromString( entity.getStarttime(), "yyyy-MM-dd HH:mm:ss");
			}catch(Exception e){
				map.put("result", "error");
				map.put("message", "开始时间格式不正确[yyyy-MM-dd HH:mm:ss]！开始时间：" + entity.getStarttime() );
				logger.error("将开始时间转换为yyyy-MM-dd HH:mm:ss格式发生异常，可能数据格式不正确！", e);
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime( starttime );
			entity.setYear( calendar.get( Calendar.YEAR ) );
			try{
				//对开始时间和结束时间进行转换，检查时间有效性，并且填写年份
				dateOperation.getDateFromString( entity.getEndtime(), "yyyy-MM-dd HH:mm:ss" );
			}catch(Exception e){
				map.put("result", "error");
				map.put("message", "结束时间格式不正确[yyyy-MM-dd HH:mm:ss]！结束时间：" + entity.getEndtime() );
				logger.error("将结束时间转换为yyyy-MM-dd HH:mm:ss格式发生异常，可能数据格式不正确！", e);
			}
		}
		
		return map;
	}
	
	/**
	 * 根据ID删除一个系统配置信息表信息
	 * 返回JSON格式数据
	 * @param int id
	**/
	@RequestMapping( method = RequestMethod.DELETE, value = "/{id}" )
    @ResponseBody
    public Object deleteById( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean check = true;
		
		map.put("id", id);
		if( id == null || id.isEmpty() || "id".equalsIgnoreCase( id )){
			check = false;
			map.put( "result", "error" );
			map.put( "message", "需要删除的信息ID为空!" );
		}
		if( check ){
			try {
				sys_holidayconfService.delete( map );
				map.put( "result", "success" );
				map.put( "message", "成功删除一个信息数据！" );
			} catch (Exception e) {
				map.put("result", "error");
				map.put("message", "删除信息数据失败!ID:" + id );
				logger.error("删除信息数据失败!ID:" + id, e);
			}
		}
		return map;
	}
	/**
	 * 根据ID删除多个系统配置信息表信息
	 * 返回JSON格式数据
	 * @param Map<String, Object> paramMap
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/delete/batch" )
    @ResponseBody
	public Object deleteByIds( @RequestBody Map<String, Object> paramMap ){
		Map<String, Object> map = new HashMap<String, Object>();
		String ids_str = null;
		Boolean check = true;
		
		if( paramMap == null || paramMap.get( "ids" ) == null ){
			check = false;
			map.put("result", "error");
			map.put("message", "参数列表为空，无法进行数据删除！");
		}
		if( check ){
			ids_str = (String)paramMap.get( "ids" );
			if( ids_str != null && ids_str.isEmpty() ){
				check = false;
				map.put("result", "error");
				map.put("message", "参数列表中ID列表为空，无法进行数据删除！");
			}else{
				map.put("ids", ids_str.split(",") );
			}
		}
		if( check ){
			try {
				sys_holidayconfService.delete( map );
				map.put("result", "success");
				map.put("message", "成功删除信息数据！");
			} catch (Exception e) {
				map.put( "result", "error");
				map.put( "message", "删除信息数据失败!ID:" + paramMap.get( "ids" ) );
				logger.error( "系统信息数据失败!ID:" + paramMap.get( "ids" ), e );
			}
		}
		return map;
	}
}
